<template>
  <div class="question-manage">
    <div class="header">
      <el-button type="primary" @click="showCreateDialog" :icon="Plus">新增试题</el-button>
    </div>
    <el-table :data="questionStore.questions" style="width: 100%">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="title" label="试题标题" width="300"  show-overflow-tooltip></el-table-column>
      <el-table-column prop="content" label="试题内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          {{ typeMap[row.type] || row.type }}
        </template>
      </el-table-column>
      <el-table-column prop="options" label="选项" width="300" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.type === 'SINGLE_CHOICE' ? row.options : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="answer" label="答案" width="300" show-overflow-tooltip></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          {{ statusMap[row.status] || row.status }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="showEditDialog(row)"
            :icon="Edit"
          >修改</el-button>
          <el-button
            :disable="row.status === 'DRAFT'"
            type="success"
            size="small"
            @click="publishQuestion(row.id)"
            :icon="Check"
          >发布</el-button>
          <el-button
            type="danger"
            size="small"
            @click="questionStore.deleteQuestion(row.id)"
            :icon="Delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增试题对话框 -->
    <el-dialog title="新增试题" v-model="createDialogVisible" width="40%">
      <el-form :model="createForm" label-width="80px" :rules="formRules" ref="createFormRef">
        <el-form-item label="试题标题" prop="title">
          <el-input v-model="createForm.title"></el-input>
        </el-form-item>
        <el-form-item label="试题内容" prop="content">
          <el-input v-model="createForm.content" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="试题类型" prop="type">
          <el-select v-model="createForm.type" placeholder="请选择类型" @change="handleTypeChange">
            <el-option label="单选题" value="SINGLE_CHOICE"></el-option>
            <el-option label="判断题" value="TRUE_FALSE"></el-option>
            <el-option label="大题" value="TEXT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选项" prop="options" v-if="createForm.type === 'SINGLE_CHOICE'">
          <el-input
            v-model="createForm.options"
            type="textarea"
            :rows="4"
            placeholder='请输入 JSON 格式选项，例如: {"A": "选项A", "B": "选项B", "C": "选项C", "D": "选项D"}'
          ></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-select
            v-if="createForm.type === 'TRUE_FALSE'"
            v-model="createForm.answer"
            placeholder="请选择答案"
          >
            <el-option label="正确" value="true"></el-option>
            <el-option label="错误" value="false"></el-option>
          </el-select>
          <el-input
            v-else
            v-model="createForm.answer"
            placeholder="请输入答案（单选题请输入选项键，如 A；大题请输入答案文本）"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createQuestion" :icon="Plus">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改试题对话框 -->
    <el-dialog title="修改试题" v-model="editDialogVisible" width="40%">
      <el-form :model="editForm" label-width="80px" :rules="formRules" ref="editFormRef">
        <el-form-item label="试题标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="试题内容" prop="content">
          <el-input v-model="editForm.content" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="试题类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择类型" @change="handleTypeChange">
            <el-option label="单选题" value="SINGLE_CHOICE"></el-option>
            <el-option label="判断题" value="TRUE_FALSE"></el-option>
            <el-option label="大题" value="TEXT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选项" prop="options" v-if="editForm.type === 'SINGLE_CHOICE'">
          <el-input
            v-model="editForm.options"
            type="textarea"
            :rows="4"
            placeholder='请输入 JSON 格式选项，例如: {"A": "选项A", "B": "选项B", "C": "选项C", "D": "选项D"}'
          ></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-select
            v-if="editForm.type === 'TRUE_FALSE'"
            v-model="editForm.answer"
            placeholder="请选择答案"
          >
            <el-option label="正确" value="true"></el-option>
            <el-option label="错误" value="false"></el-option>
          </el-select>
          <el-input
            v-else
            v-model="editForm.answer"
            placeholder="请输入答案（单选题请输入选项键，如 A；大题请输入答案文本）"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="草稿" value="DRAFT"></el-option>
            <el-option label="已发布" value="PUBLISHED"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateQuestion" :icon="Edit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Plus, Edit, Delete, Check } from '@element-plus/icons-vue';
import { useQuestionStore, Question, QuestionCreateRequest, QuestionUpdateRequest } from '@/stores/api/question';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const questionStore = useQuestionStore();

const typeMap = {
  SINGLE_CHOICE: '单选题',
  TRUE_FALSE: '判断题',
  TEXT: '大题',
};

const statusMap = {
  DRAFT: '草稿',
  PUBLISHED: '已发布',
};

const createDialogVisible = ref(false);
const editDialogVisible = ref(false);

const createForm = ref<QuestionCreateRequest>({
  title: '',
  content: '',
  type: 'SINGLE_CHOICE',
  options: '',
  answer: '',
});

const editForm = ref<QuestionUpdateRequest>({
  id: 0,
  title: '',
  content: '',
  type: 'SINGLE_CHOICE',
  options: '',
  answer: '',
  status: 'DRAFT',
});

const formRules = ref<FormRules>({
  title: [{ required: true, message: '请输入试题标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入试题内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择试题类型', trigger: 'change' }],
  options: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if ((createForm.value.type === 'SINGLE_CHOICE' || editForm.value.type === 'SINGLE_CHOICE') && !value) {
          callback(new Error('单选题必须输入选项'));
        } else if (value) {
          try {
            JSON.parse(value);
            callback();
          } catch {
            callback(new Error('选项必须为有效 JSON 格式'));
          }
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  answer: [{ required: true, message: '请输入答案', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
});

const createFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const showCreateDialog = () => {
  createForm.value = { title: '', content: '', type: 'SINGLE_CHOICE', options: '', answer: '' };
  createDialogVisible.value = true;
};

const showEditDialog = (question: Question) => {
  editForm.value = { ...question, id: question.id, status: question.status };
  editDialogVisible.value = true;
};

const handleTypeChange = () => {
  // 切换类型时清空选项和答案
  createForm.value.options = '';
  createForm.value.answer = '';
  editForm.value.options = '';
  editForm.value.answer = '';
};

const createQuestion = async () => {
  if (!createFormRef.value) return;
  createFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await questionStore.createQuestion(createForm.value);
        createDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const updateQuestion = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await questionStore.updateQuestion(editForm.value);
        editDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const publishQuestion = async (id: number) => {
  try {
    await questionStore.publishQuestion(id);
  } catch (error) {
    // 错误已在 store 中处理
  }
};

onMounted(() => {
  questionStore.fetchQuestions();
});
</script>

<style scoped>
.question-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}

.el-button i + span {
  margin-left: 8px;
}

.el-select,
.el-input {
  width: 100%;
}
</style>